package com.xx.douyi.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.IterableUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Description: com.xx.douyi.controller
 * @Author: ruby
 * @CreateTime: 2023-02-04 12:33
 */

@Slf4j
@Controller
public class HomeController {
    @Autowired
    DouYinController douYinController;
    @Autowired
    BossZPController bossZPController;
    @RequestMapping("/")
    public String index(ModelMap modelMap){
        Map code = douYinController.getCode();
        modelMap.put("code",code);
        return "index";
    }

    @RequestMapping("/boss")
    public String boss(ModelMap modelMap){
        Map msg = bossZPController.getMsg(null, null);
        modelMap.put("data",msg);
        return "boss";
    }

    @SneakyThrows
    @PostMapping("/readExcel")
    @ResponseBody
    public Set<Object> readExcel(@RequestParam("file") MultipartFile file, @RequestParam("index") int index){
        //获取excel
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream(),index);
        HashSet<Object> objects1 = new HashSet<>();
        //获取计算公式
        FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) reader.getWorkbook());
        //读取表 遍历所有行并跳过第一行
        for (Row cells : IterableUtils.skippingIterable(reader.getSheet(),1)) {
            List<String> objects = new ArrayList<>();
            //获取房屋大小
            objects.add(calcType(formulaEvaluator,cells.getCell(14)));
            //获取size
            objects.add(calcType(formulaEvaluator,cells.getCell(15)));
            objects1.add(objects);
        }
        return objects1;
    }

    String calcType(FormulaEvaluator formulaEvaluator,Cell cell){
        CellType cellType = cell.getCellType();
        switch (cellType){
            case FORMULA:
                CellValue value = formulaEvaluator.evaluate(cell);
                String s = value.formatAsString().replaceAll("\"", "");
                return s;
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case STRING:
                return cell.getStringCellValue();
        }
        return null;
    }
}
